import { registerApi } from "@/api";
import MyInput from "@/components/MyInput";
import { View, Text } from "@tarojs/components";
import Taro, { useLoad } from "@tarojs/taro";
import { useState } from "react";
import { toast, isValidEmail, isValidPhone } from "@/utils";
import { Checkbox } from "@taroify/core";

export default () => {
  useLoad(() => {
    Taro.setNavigationBarTitle({ title: "注册" });
  });
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [pwd, setPwd] = useState("");
  const [repwd, setRePwd] = useState("");
  const [checked, setChecked] = useState(false);

  function register() {
    if (!email || !isValidEmail(email)) return toast("请输入正确的邮箱地址");
    if (!phone || !isValidPhone(phone)) return toast("请输入正确的手机号码");
    if (!pwd) return toast("请先输入密码");
    if (pwd !== repwd) return toast("两次输入的密码不一致");
    if (!checked) return toast("请同意用户协议");
    registerApi({ email, phone, password: pwd }).then(() => {
      toast("注册成功", "success", 3000);
      setTimeout(() => Taro.switchTab({ url: "pages/index/index" }), 2000);
    });
  }

  return (
    <View className=" px-7">
      <View className="flex flex-col gap-4 mt-32">
        <MyInput left="+86 |" placeholder="请输入手机号码" change={setPhone} />
        <MyInput placeholder="请输入邮箱地址" change={setEmail} />
        <MyInput placeholder="请输入密码" type="password" change={setPwd} />
        <MyInput placeholder="请确认密码" type="password" change={setRePwd} />
      </View>
      <View className="flex text-gray-400 flex-col justify-center items-center gap-3 my-5">
        <View
          onClick={register}
          className="w-full  text-center py-2 bg-[#73D0EF] text-white rounded-lg"
        >
          注册
        </View>
        <View className="flex justify-center items-center">
          <Checkbox
            shape="square"
            onChange={setChecked}
            checked={checked}
            size={20}
          >
            <View className="text-xs">
              已经阅读并同意
              <Text className="text-[#7896BC]">《用户服务协议》</Text>
            </View>
          </Checkbox>
        </View>
        <View>忘记密码？</View>
      </View>
    </View>
  );
};
